package tp1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;


public class ClientChat extends Thread {

    Client clientParent; 
    private DatagramSocket socket;

    public ClientChat(DatagramSocket ds) {
        this.socket = ds;
        this.clientParent = Client.getInstance();
    }

    public void run() {
        String sentence, userFrom,msgRecu,nMsg;
        String couleurChat = clientParent.ANSI_CYAN;
        clientParent.debug(clientParent.ANSI_PURPLE+"[ServeurChat v2] Ready. Adresse " +clientParent.adresseLocale.getHostAddress() + " port " + socket.getLocalPort()+clientParent.ANSI_RESET);

        while (true) {
            byte[] msg = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(msg, msg.length);
            try {
                socket.receive(receivePacket);
                sentence = new String(receivePacket.getData());
                nMsg = sentence.substring(3,5);
                userFrom = sentence.substring(5,11);
                msgRecu = sentence.substring(11);

                clientParent.debug("[Client Chat] Msg reçu de " + receivePacket.getAddress() + " port " + receivePacket.getPort() + "\n---->" + sentence);
                System.out.println(couleurChat+"["+userFrom+" #"+nMsg+" ] "+clientParent.ANSI_RESET+msgRecu);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
